var Max_FILE_SIZE = "10mb";
var READ_ONLY = "10";
var CAN_EDIT = "01";
var Max_FILE_SIZE_DATA = 1024*1024*10;
var header = $("meta[name='_csrf_header']").attr("content");
var token = $("meta[name='_csrf']").attr("content");
var UploadFileManager = {
    containers:{},
    getUploadFileById:function(id){
        return this.containers[id];
    },
    setUploadFile:function(grid){
        this.containers[grid.settings.divId] = grid;
    }
};

var UploadComponent = function(settings){
    this.settings = {
        fileFilter:"*",
        fileDescription:"File(*)",
        downloadUrl:"",
        //initUrl:"fileUpload/find",
        containerId:"",
        showDownAll:true,
        divId:"",
        inputDiv:"",
        canEditType:{xls:true,xlsx:true,doc:true,docx:true,wps:true},
        //deleteUrl:"fileupload/delete"
    };
    if(settings["fileType"]&&settings["fileType"].indexOf("|")>0){
        var filters = settings["fileType"].split("|");
        this.settings.fileDescription = filters[0];
        this.settings.fileFilter = filters[1];
    }
    if(settings.containerId){
        this.containerId = settings.containerId;
    }
    $.extend(this.settings,settings);
    this.settings.readOnly = $("#"+this.settings.divId).attr("readOnly");
    this.init();
    UploadFileManager.setUploadFile(this);
};


UploadComponent.prototype = {
    init:function(){
        var g = this;
        g.fileCounts = 0;
        g.isCanUpload = true;
        g.buildTable();
        g.createUrl();
        g.uploader ;
        //this.showFileList();
    },




     buildTable:function(){
        var g = this;
        var tables = new Array();
        if (this.settings.styleType == "normal") {
            tables.push('<form id="' + this.getContainerId() + '" action="' + this.settings.uploadUrl + '" method="post" onchange="uploadFile(' + this.getContainerId() + ')" enctype="multipart/form-data">');
            tables.push('<input type="file" name="myFile"  />');
            tables.push('<input type="text" name="fileName" id="fileName" placeholder="请上传,附件大小≤100M" onmouseover="this.title=this.value" class="form-control no-border" />');
            tables.push('<input type="hidden" name="fileType" value="'+ this.settings.fileType +'"  />');
            tables.push('<input type="button"   value="上传">');
            tables.push('<span class="percent" id="attachment">0%</span>');
            tables.push('</form><br/>');
        } else if (this.settings.styleType == "ace") {
            tables.push('<div class="main-container"><div class="page-content"><div class="row"><div class="center" style="width:400px; margin:12px;"><h3 class="header blue smaller lighter">上传附件</h3>' +
            '<form id="'+this.getContainerId()+'" method="post" action="fileUpload/customerFile" onchange="upload4ace(this)"><input  type="file" name="myFile"   /><div class="hr hr-12 dotted"></div></form></div></div></div></div>');
        }
        $("#"+this.settings.divId).append(tables.join(""));
        if (this.settings.styleType == "ace") {
            var $form = $('#' + this.getContainerId());
            var file_input = $form.find('input[type=file]');
            var upload_in_progress = false;
            var ie_timeout = null;
            file_input.ace_file_input({
                style: 'well',
                btn_choose: 'Select or drop files here',
                btn_change: null,
                droppable: true,
                thumbnail: 'large',
                maxSize: 1100000000,//bytes
                before_remove: function () {
                    if (upload_in_progress)
                        return false;//if we are in the middle of uploading a file, don't allow resetting file input
                    return true;
                },
                preview_error: function (filename, code) {
                }
            })
        }


    },


    addEvent:function(){

    },
    afterLoaded:function(file,resp){
        var g = this;
        $("#"+g.settings.inputDiv,$("#"+g.settings.divId)).val(resp["documentID"]);
        g.showDownAll();
        $('.fileName',$("#"+file.id)).html("<a href='"+g.settings.downloadUrl + "?attachmentId="+resp["attachmentID"]+"'>"+$('.fileName',"#"+file.id).html()+"</a>");
        $('.deleteBtn',$("#"+file.id)).unbind("click");
        $('.deleteBtn',$("#"+file.id)).bind("click",function(){
            if(confirm("您确实要删除附件:"+file.name)){
                $.ajax({ type:"post", url: g.settings.deleteUrl, data: {attachmentId:resp["attachmentID"]},success: function(){
                    $("#"+file.id).parent().remove();
                    g.fileCounts -= 1;
                },fail:function(){
                    //alert("文件被使用,删除失败")
                    $.zui.messager.show("文件被使用,删除失败", {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
                } });
            }
        });
        $('.updateBtn',$("#"+file.id)).unbind("click").bind("click",function(){
            window.open(g.settings.editUrl+"?attachmentId="+resp["attachmentID"]+"&isReadOnly="+(g.settings.readOnly?"true":"false"));
        });
    } ,
    createUrl:function(){
        var g = this;
        var documentId = g.settings.documentId||g.getDocId();
        if(this.settings.uploadUrl.indexOf("?")>0){
            this.settings.uploadUrl = this.settings.uploadUrl.substr(0,this.settings.uploadUrl.indexOf("?"));
        }
        var hide = $("#"+this.settings.divId).attr("hide")||"";
        if(hide){
            hide = 9;
        }
        //this.settings.uploadUrl += "?code=" + (this.settings.code||$(".fileUpload","#"+g.settings.divId).attr("code"));
        //this.settings.uploadUrl +=  "&hide="+hide;
        //添加阶段判断
        var period =  $("#"+this.settings.divId).attr("period")||"";
        if(period){
            this.settings.uploadUrl +=  "&period="+period;
        }

        if(this.settings.uploadUrl.indexOf("document_ID")>0){
            this.settings.uploadUrl = this.settings.uploadUrl.substr(0,this.settings.uploadUrl.indexOf("document_ID")-1);
        }

        if(documentId&&documentId!="0"){
            //this.settings.uploadUrl = this.settings.uploadUrl +"&document_ID="+documentId;
        }
        if(g.uploader){
            g.uploader.settings.url =  this.settings.uploadUrl;
        }
    },

    startUpload:function(){
        this.uploader.start();
        return false;
    },
    showDownAll:function(){
        var g = this;
        var docId = g.getDocId();
        if(docId&& g.getIsShowDownAll()){
            var downAllSpan = $(".downAll","#"+g.settings.divId);
            downAllSpan.find("a").attr("href", g.settings.downloadAllUrl+"?docId="+docId);
            downAllSpan.show();
        }
    } ,
    getIsShowDownAll:function(){
        var g = this;
        return this.settings.showDownAll||($("#"+this.settings.divId).attr("canEdit")=="true");
    },
    generateId:function(){
        return "upload_"+ (new Date().getTime() + Math.floor(Math.random()*1000000));
    },
    getContainerId:function(){
        if(!this.containerId){this.containerId = this.generateId();}
        return this.containerId;
    },
    getFileListId:function(){
        if(!this.fileListId){this.fileListId = this.generateId();}
        return this.fileListId;
    },
    getBrowseButtonId:function(){
        if(!this.BrowserRowId){this.BrowserRowId = this.generateId();}
        return this.BrowserRowId;
    },
    createDocElement:function(params){
        var g = this;
        var addFileArray = new Array();
//        addFileArray.push($('#'+g.getFileListId()).html());
        if(params.period&&params.period!= g.period){
            if(params["index"]>0){
                addFileArray.push('<div  style="float:left;color: red;font-size:12px;font-weight: bold;margin-top:2px;">|</div > ');
            }
            g.period = params.period;
        }
        addFileArray.push( '<div style="float:left;margin-left: 20px;margin-top:2px;font-size: 12px;color: #000000;font-weight: bold;" >');

        addFileArray.push( '<div id="' + params.attachmentId + '" ><input class="ico_att" style="margin-top: 2px; margin-right: 3px; margin-bottom: 2px; margin-left: 0px;" type="button"/><span class="fileName">'+ params.fileName+"</span>");
        var period =  $("#"+this.settings.divId).attr("period")||"";
        if(!g.settings.readOnly){
            if(period){
                if(period==params["period"]){
                    addFileArray.push('<span class="deleteBtn" style="cursor:pointer;margin-left: 12px">&nbsp;&nbsp;</span>');
                }
            }else{
                addFileArray.push('<span class="deleteBtn" style="cursor:pointer;margin-left: 12px">&nbsp;&nbsp;</span>');
            }
        }
        if(g.isCanEdit(params.fileName)){
            addFileArray.push('<span class="updateBtn" style="cursor:pointer;margin-left: 12px" title="编辑">&nbsp;&nbsp;</span>');
        }

        addFileArray.push('</div>');
        addFileArray.push('</div>');


        $('#'+g.getFileListId()).append(addFileArray.join(""));
        $('.fileName',$("#"+g.settings.divId).find("#"+params.attachmentId)).html("<a href='"+g.settings.downloadUrl + "?attachmentId="+params["attachmentId"]+"' style='color: grey;'>"+$('.fileName',"#"+params.attachmentId).html()+"</a>");
        $('.deleteBtn',$("#"+g.settings.divId).find("#"+params.attachmentId)).click(function(){
            if(confirm("您确实要删除附件:"+params.fileName)){
                $.ajax({ type:"post", url: g.settings.deleteUrl, data: {attachmentId:params["attachmentId"]},success: function(){
                    $("#"+ params.attachmentId).parent().remove();
                    g.fileCounts -= 1;
                },fail:function(){
                    //alert("文件被使用,删除失败")
                    $.zui.messager.show("文件被使用,删除失败", {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
                } });
            }
        });
        $('.updateBtn',$("#"+g.settings.divId).find("#"+params.attachmentId)).bind("click",function(){
            window.open(g.settings.editUrl+"?attachmentId="+params["attachmentId"]+"&isReadOnly="+(g.settings.readOnly?"true":"false"));
        });
        addFileArray = null;
        delete addFileArray;
    } ,
    showFileList:function(docId){
        var g = this;
        $('#'+g.getFileListId()).html("");
        var documentId = docId||g.settings.documentId||this.getDocId();
        var orderBy = $("#"+g.settings.divId).attr("orderBy");
        g.showDownAll();
        if(documentId&&documentId!="0") {
            $.ajax({
                type:"post",
                url: g.settings.initUrl,
                data: {documentId:documentId,orderBy:orderBy},
                dataType: 'json',
                success: function(datas){
                    g.fileCounts = datas.length;
                    // $('#'+g.getFileListId()).find('.clear').remove();
                    $.each(datas,function(index){
                        var params = {attachmentId:this.attachmentID,fileName:this.fileName,deleteUrl:g.settings.deleteUrl,downloadUrl:g.settings.downloadUrl,author:this.author,key:this.key,summary:this.summary,readOnly:this.readOnly,period:this.period,index:index};
                        g.createDocElement(params)
                    });
                    //$('#'+g.getFileListId()).append("<div class='clear' style='clear: both;'></div>");
                },
                //error: function() {}// {alert("加载失败")}
                error:function(jqXHR, textStatus, errorThrown)
                {
                    jqXHR;
                    textStatus;
                    errorThrown;
                }
            });
        }

    },
    //设置附件上传控件是否只读
    setReadOnly:function(flag){
        var g = this;
        if(flag){
            $(".footer",$("#"+g.settings.divId)).hide();
        }else{
            $(".footer",$("#"+g.settings.divId)).show();
        }
        g.settings.readOnly = flag;
    },
    setFileReadOnly:function(flag){
        this.setReadOnly(flag);
        this.showFileList();
    },
    setDocId:function(docId){
        var g = this;
        if(docId==0||docId=="0"){
            docId = "";
        }
        if(!docId){
            g.fileCounts = 0;
        }
        g.settings.documentId = docId;
        $("#"+g.settings.inputDiv,$("#"+g.settings.divId)).val(docId);
        this.createUrl();
        this.showFileList();
    },
    getDocId:function(){
        var g = this;
        return  $("#"+g.settings.inputDiv,$("#"+g.settings.divId)).val();
    },
    reset:function(){
        this.setDocId("");
    }

};


function uploadFile(formId) {
    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');



    $('#'+formId.id).submit();
   $('#'+formId.id).ajaxSubmit({
        beforeSend: function (xhr) {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal)
            percent.html(percentVal);
            //xhr.setRequestHeader(header, token);
        },
        uploadProgress: function (event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
            percent.html(percentVal);
            //console.log(percentVal, position, total);
        },
        success: function (data) {
            var percentVal = '100%';
            bar.width(percentVal)
            percent.html(percentVal);
            //console.log(data);
            //var dataObj = JSON.parse(data.attachmentsVo);

            //这里加入自处理的回调函数 注意 form 的 containerId 定义方式为 divId_upload_form ，divId为上传容器ID 方便获取到上传参数的回调函数
            //定义样例 new UploadComponent({divId:'attachment',containerId:'attachment_upload_form',success:function(data){}});
            //BEGIN
            var divId = formId.id.replace('_upload_form','');
            var uploadComponent = UploadFileManager.getUploadFileById(divId);
            if(uploadComponent && uploadComponent.settings){
                var callback = uploadComponent.settings.success;
                callback && callback.call(uploadComponent,data);
            }else{
                $("#attachment").append("<td>"+dataObj.originalFilename+" "+dataObj.fileSize+"字节");
            }
            //END

        },
        complete: function (xhr) {
            status.html(xhr.responseText);
        }
    });



}



function upload4ace(target){
    var $form = $('#'+target.id);
    var file_input = $form.find('input[type=file]');
    var upload_in_progress = false;
    var ie_timeout = null;
    file_input.ace_file_input({
        style : 'well',
        btn_choose : 'Select or drop files here',
        btn_change: null,
        droppable: true,
        thumbnail: 'large',
        maxSize: 1100000000,//bytes
        before_remove: function() {
            if(upload_in_progress)
                return false;//if we are in the middle of uploading a file, don't allow resetting file input
            return true;
        },
        preview_error: function(filename , code) {
        }
    })
    $form.ajaxSubmit({
        beforeSend: function (xhr) {
            var percentVal = '0%';
            xhr.setRequestHeader(header, token);
        },
        uploadProgress: function (event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
        },
        success: function (data) {
            var percentVal = '100%';
            var dataObj = JSON.parse(data);
            //alert(dataObj.fileName+" upload success !");
            $.zui.messager.show(dataObj.fileName+" upload success !", {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        },
        complete: function (xhr) {
            if(ie_timeout) clearTimeout(ie_timeout)
            ie_timeout = null;
            upload_in_progress = false;
            file_input.ace_file_input('loading', false);
        }
    });

}

//清空file按钮
function excelClicke() {
    //$('#excelUpload')[0].reset();
    var file = document.getElementById("file");
    if (file.outerHTML) {
        file.outerHTML = file.outerHTML;
     } else {
        file.value = "";
     }
}
